//
//  MeetingViewController.swift
//  visionos_test_demo
//
//  Created by 3tee on 2024/7/26.
//

import UIKit
import rtc_sdk_vision
import SwiftUI
class MeetingViewController: UIViewController {

    var mroom: AVDRoom?
    var mvideo: AVDVideo?
    var maudio: AVDAudio?
    var musermanager: AVDUserManager?
    var mscreen: AVDScreen?
    var whiteboard: AVDWhiteboard?
    var canvasView: AVDCanvasView?
    var boardinfo: AVDWhiteboardInfo!
    var renderArr = NSMutableArray()
    lazy var usersVC: UsersSwiftUIController = {
        return UsersSwiftUIController()
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
        configMoudle();
        NotificationCenter.default.post(name:Notification.Name(NotificationName.updateList), object: nil)

    }

    func configMoudle() {
        if let roomid = UserDefaults().string(forKey:K.roomId) {
            self.view.backgroundColor = .orange
            mroom = AVDRoom.obtain(roomid)
            mroom?.delegate = self
            mvideo = AVDVideo.getVideo(mroom)
            mvideo?.delegate = self
            maudio = AVDAudio.getAudio(mroom)
            musermanager = AVDUserManager.getUserManager(mroom)
            mscreen = AVDScreen.getScreen(mroom)
            mscreen?.delegate = self
            whiteboard = AVDWhiteboard.getWhiteboard(mroom)
            whiteboard?.delegate = self
            displayPublishedCameras()
        }
    }
    func configUI() {
        self.view.addObserver(self, forKeyPath: "frame", options: .new, context: nil)
        self.navigationItem.hidesBackButton = true
        for subView in self.view.subviews {
            if subView.isKind(of: UIButton.self) {
                subView.layer.cornerRadius = 30
                subView.layer.masksToBounds = true
            }
            if subView.isKind(of: UIStackView.self) {
                for stackV in subView.subviews{
                    if stackV.isKind(of: UIStackView.self) {
                        for render in stackV.subviews{
                            if render.isKind(of: AVDVideoView.self) {
                                addNameLab(render: render as! AVDVideoView)
                                render.layer.borderWidth = 1
                                render.layer.borderColor = UIColor.white.cgColor
                                renderArr.add(render)
                            }
                        }
                    }
                }
            }
        }
      
    }
    //订阅渲染自己加入房间之前已经发布的视频流
    func displayPublishedCameras()  {
        mvideo?.publishedCameras.enumerateObjects({ camera, idx, stop in
            let cam = camera as! AVDCamera
            mvideo?.subscribe(cam.id)
            let freeRender = getFreeRender()
            let lab = freeRender.viewWithTag(666) as? UILabel
            let userid =  mvideo?.getOwnerId(cam.id)
            let user = musermanager?.getUser(userid)
            lab?.text = user?.userName
            mvideo?.attachRender(withDeviceId: cam.id, render: freeRender)
        })
    }
    
    override func viewDidLayoutSubviews() {
        canvasView = AVDCanvasView(frame: CGRect(x: 0, y: 0, width: CGRectGetWidth(self.view.frame), height: CGRectGetHeight(self.view.frame) - 100))
        //canvasView?.backgroundColor = UIColor.red
        self.view.addSubview(canvasView!)
    }
    
    func addNameLab(render: AVDVideoView) {
        let lab = UILabel()
        render.addSubview(lab)
        lab.translatesAutoresizingMaskIntoConstraints = false
        // 添加左边约束
        let leftConstraint = NSLayoutConstraint(item: lab, attribute: .left, relatedBy: .equal, toItem: render, attribute: .left, multiplier: 1, constant: 20)
        
        // 添加底部约束
        let bottomConstraint = NSLayoutConstraint(item: lab, attribute: .bottom, relatedBy: .equal, toItem: render, attribute: .bottom, multiplier: 1, constant: -20)
        
        // 应用约束
        NSLayoutConstraint.activate([leftConstraint, bottomConstraint])
        lab.textColor = .darkText
        lab.font = UIFont.systemFont(ofSize: 24)
        lab.backgroundColor = .white
        lab.sizeToFit()
        lab.tag = 666
    }
    
    // 当view的frame发生变化时，会调用此方法
       override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
           GeometryReader { geometry in
               let size = CGSize(width: geometry.size.width, height: geometry.size.height)
               Text("Width: \(geometry.size.width), Height: \(geometry.size.height)")

            }
           if keyPath == "frame" {
               // 这里处理frame变化的逻辑
               if let newFrame = change?[.newKey] as? CGRect {
                   print("Render's new frame is \(newFrame)")
               
               }
           }
       }
    
    func getFreeRender() -> AVDVideoView {
        for view in renderArr{
            if let render = view as? AVDVideoView {
                if render.getVideoId() == nil {
                    return render
                }
            }
        }
        return AVDVideoView()
    }
    
    func getRender(with id: String) -> AVDVideoView {
        for view in renderArr {
            if let render = view as? AVDVideoView {
                if render.getVideoId() == id {
                    return render
                }
            }
        }
        return AVDVideoView()
    }

    @IBAction func micClicked(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        sender.isSelected ? maudio?.openMicrophone():maudio?.closeMicrophone()
    }
    
    @IBAction func leaveClicked(_ sender: UIButton) {
        mroom?.leave(0)
        mroom?.destory()
        navigationController?.popViewController(animated: true)
        NotificationCenter.default.post(name:Notification.Name(NotificationName.clearList), object: nil)

    }
    
    
    @IBAction func usersClicked(_ sender: UIButton) {
        NotificationCenter.default.post(name:Notification.Name(NotificationName.updateList), object: nil)
    }
    
    @IBAction func shareScreenClicked(_ sender: UIButton) {
        let size = CGSizeMake(view.frame.size.width + 202, view.frame.size.height)
        print("publish screen size = \(size)")
        mscreen?.publishScreenSize(size, fps: 15)
    }
    
    @IBAction func boardClicked(_ sender: UIButton) {
    }
    
    
}


extension MeetingViewController: AVDVideoDelegate{
    func onPublishLocalResult(_ result: AVDResult, deviceId fromId: String!) {
        
    }
    
    func onUnpublishLocalResult(_ result: AVDResult, deviceId fromId: String!) {
                
    }
    
    func onCameraStatusNotify(_ status: AVDDeviceStatus, deviceId fromId: String!) {
        
    }
    
    func onPublishCameraNotify(_ camera: AVDCamera!) {
  
        self.mvideo?.subscribe(camera.id)
        let freeRender = getFreeRender()
        let lab = freeRender.viewWithTag(666) as? UILabel
        let userid =  mvideo?.getOwnerId(camera.id)
        let user = musermanager?.getUser(userid)
        lab?.text = user?.userName
        self.mvideo?.attachRender(withDeviceId: camera.id, render: freeRender)
       
    }
    
    func onUnpublishCameraNotify(_ camera: AVDCamera!) {
        self.mvideo?.unsubscribe(camera.id)
        let attachRender = getRender(with: camera.id)
        let lab = attachRender.viewWithTag(666) as? UILabel
        lab?.text = nil
        self.mvideo?.detachRender(withRender: attachRender)
        
    }
    
}

extension MeetingViewController: AVDRoomDelegate{
    func onLeaveIndication(_ reason: AVDResult, fromUser fromId: String!) {
        mroom?.destory()
        navigationController?.popViewController(animated: true)
    }
    
    func onConnectionStatus(_ status: AVDConnectionStatus) {
        if status == AVDConnectionStatus(connecting.rawValue){
            AlertTool().show("断线重连中，，，，，", in: self.view)
        }else if status == AVDConnectionStatus(connected.rawValue){
            AlertTool().show("断线重连成功🤭🤭🤭🤭", in: self.view)
        }else{
            AlertTool().show("断线重连失败☹️☹️☹️☹️", in: self.view)

        }
    }
    
}

extension MeetingViewController: AVDScreenDelegate{
    func onScreenStatusNotify(_ status: AVDDeviceStatus, deviceId fromId: String!) {
        
    }
    
    func onPublishScreenNotify(_ screen: AVDVideoDevice!) {
        self.mscreen?.subscribe(screen.id)
        let freeRender = getFreeRender()
        let lab = freeRender.viewWithTag(666) as? UILabel
        let userid =  mscreen?.getOwnerId(screen.id)
        let user = musermanager?.getUser(userid)
        lab?.text = user?.userName
        self.mvideo?.attachRender(withDeviceId: screen.id, render: freeRender)
    }
    
    func onUnpublishScreenNotify(_ screen: AVDVideoDevice!) {
        self.mscreen?.unsubscribe(screen.id)
        let attachRender = getRender(with: screen.id)
        let lab = attachRender.viewWithTag(666) as? UILabel
        lab?.text = nil
        self.mscreen?.detachRender(withRender: attachRender)
    }
}


extension MeetingViewController: AVDWhiteboardDelegate{
    func onCreateLocalBoardNotify(_ whiteboardId: String!, result: AVDResult) {
        
    }
    func onCreateBoardNotify(_ whiteboardInfo: AVDWhiteboardInfo!) {
        
    }
    
    func onShareBoardNotify(_ whiteboardInfo: AVDWhiteboardInfo!) {
        boardinfo = whiteboardInfo
        canvasView?.isHidden = false
        whiteboard?.attach(canvasView, boardInfo: whiteboardInfo)
    }
    
    func onCloseBoardNotify(_ whiteboardId: String!) {
        whiteboard?.dettachView(canvasView, boardId: whiteboardId )
        canvasView?.isHidden = true
        
    }
    
    func onRemoveBoardNotify(_ whiteboardId: String!) {
        whiteboard?.dettachView(canvasView, boardId: whiteboardId )
        canvasView?.isHidden = true
    }
}

